package com.michaelbulava.TFS.common.item;

import com.microsoft.tfs.core.clients.versioncontrol.path.ServerPath;
import com.microsoft.tfs.util.Check;

public class ServerItemPath
{
    public static final ServerItemPath ROOT = new ServerItemPath("$/");
    private final String fullPath;

    public ServerItemPath(String path)
    {
        Check.notNull(path, "path");

        fullPath = ServerPath.canonicalize(path);
    }

    public String getFullPath()
    {
        return fullPath;
    }

    public String getFilePart()
    {
        return ServerPath.getFileName(fullPath);
    }

    public String getName()
    {
        if (isRoot()) {
            return "$";
        }
        return ServerPath.getFileName(fullPath);
    }

    public ServerItemPath getParent()
    {
        if (isRoot()) {
            return null;
        }
        return new ServerItemPath(ServerPath.getParent(fullPath));
    }

    public boolean isRoot()
    {
        return ServerPath.equals(fullPath, "$/");
    }

    public boolean isParentOf(ServerItemPath possibleChild)
    {
        return ServerPath.isChild(fullPath, possibleChild.getFullPath());
    }

    public boolean isStrictParentOf(ServerItemPath possibleChild)
    {
        return (isParentOf(possibleChild)) && (!equals(possibleChild));
    }

    public ServerItemPath combine(String relative)
    {
        return new ServerItemPath(ServerPath.combine(fullPath, relative));
    }

    public String toString()
    {
        return fullPath;
    }

    public boolean equals(Object obj)
    {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof ServerItemPath)) {
            return false;
        }
        ServerItemPath other = (ServerItemPath)obj;
        return ServerPath.equals(fullPath, other.getFullPath());
    }

    public int hashCode()
    {
        return fullPath.toLowerCase().hashCode();
    }

    public int getFolderDepth()
    {
        return ServerPath.getFolderDepth(fullPath);
    }

    public String getPathSection(int index)
    {
        return split()[index];
    }

    public ServerItemPath getTeamProject()
    {
        if (isRoot()) {
            return null;
        }
        return getHierarchy()[1];
    }

    private String[] split()
    {
        String[] split = ServerPath.split(fullPath);
        if (ServerPath.equals(split[0], "$/")) {
            split[0] = "$";
        }
        return split;
    }

    public ServerItemPath[] getHierarchy()
    {
        String[] paths = ServerPath.getHierarchy(fullPath);
        if (paths == null) {
            return null;
        }
        ServerItemPath[] items = new ServerItemPath[paths.length];
        for (int i = 0; i < paths.length; i++) {
            items[i] = new ServerItemPath(paths[i]);
        }
        return items;
    }
}

